package helpers

import (
	"io/ioutil"
	"net/http"
	"net/url"
	"unicode"
)

func GetFileList(path string, dirName string) []string {
	fs, err := ioutil.ReadDir(path)
	if err != nil {
		panic(err)
	}
	res := []string{}
	for _,file:=range fs{
		fileName := file.Name()
		if !file.IsDir() {
			if dirName != "" {
				fileName = dirName +"/"+ fileName
			}
			res = append(res, fileName)
		} else {
			resChild := GetFileList(path + "/" + fileName + "/", fileName)
			res = append(res, resChild...)
		}
	}
	return res
}

func Ucfirst(str string) string {
	for i, v := range str {
		return string(unicode.ToUpper(v)) + str[i+1:]
	}
	return ""
}

func Lcfirst(str string) string {
	for i, v := range str {
		return string(unicode.ToLower(v)) + str[i+1:]
	}
	return ""
}

func Post(url string, post url.Values) (string, error) {
	resp, err := http.PostForm(url, post)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(result), err
	/*
	data := map[string]interface{}{}
	err = json.Unmarshal(result, &data)
	if err != nil {
		return nil, err
	}
	return data, nil

	 */
}

func Get(url string, param url.Values) (string, error) {
	str := ""
	for k, v := range param {
		str += k +"="+v[0] + "&"
	}
	url += "?" + str
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	result, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(result), err
	/*
		data := map[string]interface{}{}
		err = json.Unmarshal(result, &data)
		if err != nil {
			return nil, err
		}
		return data, nil

	*/
}